
import React, {
    Component,
    PropTypes
} from 'react';

import ReactNative, {
    EdgeInsetsPropType,
    Image,
    NativeMethodsMixin,
    Platform,
    requireNativeComponent,
    StyleSheet,
    View,
    UIManager
} from 'react-native';

export default class YuanXinPlayerView extends Component {

    static defaultProps = {
    };  // 注

    static propTypes = {
        ...View.propTypes,
        /**
         * Used to style and layout the `MapView`.  See `StyleSheet.js` and
         * `ViewStylePropTypes.js` for more info.
         */
        style: View.propTypes.style,
        contentInset: EdgeInsetsPropType,
        url: PropTypes.string.isRequired,
        onPlayBackState: PropTypes.func,
        /**
         * 出错时调用的接口
         */
        onError: PropTypes.func
    }

    constructor(props) {
        super(props);
        this.onPlayBackState = this._onPlayBackState.bind(this);
        this.currentError = this._onError.bind(this);
    }

    _onPlayBackState(event: Event) {
        var playBackState = this.props.onPlayBackState;
        if (playBackState) {
            playBackState(event);
        }
    }

    _onError(event: Event) {
        var onError = this.props.onError;
        if (onError) {
            onError(event);
        }
    }

    componentDidMount() {
        this.start();
    }

    //组件移除
    componentWillUnmount() {
        this.shutdown();
    }


    start() {
        UIManager.dispatchViewManagerCommand(
            this.getViewHandle(),
            UIManager.YuanXinPlayer.Commands.start,
            []
        );
    }

    stop() {
        UIManager.dispatchViewManagerCommand(
            this.getViewHandle(),
            UIManager.YuanXinPlayer.Commands.stop,
            []
        );
    }

    resume() {
        UIManager.dispatchViewManagerCommand(
            this.getViewHandle(),
            UIManager.YuanXinPlayer.Commands.resume,
            []
        );

    }

    pause() {
        UIManager.dispatchViewManagerCommand(
            this.getViewHandle(),
            UIManager.YuanXinPlayer.Commands.pause,
            []
        );
    }

    shutdown() {
        UIManager.dispatchViewManagerCommand(
            this.getViewHandle(),
            UIManager.YuanXinPlayer.Commands.shutdown,
            []
        );
    }

    seekTo(currentPlaybackTime: Number) {
        UIManager.dispatchViewManagerCommand(
            this.getViewHandle(),
            UIManager.YuanXinPlayer.Commands.seekTo,
            [currentPlaybackTime]
        );
    }

    getViewHandle() {
        return ReactNative.findNodeHandle(this.refs["playerView"]);
    }

    render() {
        return <PlayerView ref="playerView" {...this.props} onPlayBackState={this.onPlayBackState} onError={this.currentError} />;
    }
}

var PlayerView = requireNativeComponent('YuanXinPlayer', YuanXinPlayerView);
